package com.grsu.phonestation.web;


import org.springframework.stereotype.Controller;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

import com.grsu.phonestation.domain.Client;

@Controller
public class RegistrationValidator implements Validator {

	private String repeatPassword;

	private boolean loginBusy;

	private boolean emailBusy;

	@Override
	public boolean supports(Class<?> clazz) {
		return Client.class.equals(clazz);
	}

	@Override
	public void validate(Object target, Errors errors) {

		ValidationUtils.rejectIfEmpty(errors, "login", "field.required", "Login not be empty.");
		if (loginBusy) {
			errors.rejectValue("login", "field.required", "This login is already exists.");
		}

		ValidationUtils.rejectIfEmpty(errors, "firstname", "field.required", "Firstname not be empty.");

		ValidationUtils.rejectIfEmpty(errors, "lastname", "field.required", "Lastname not be empty.");

		ValidationUtils.rejectIfEmpty(errors, "password", "field.required", "Password not be empty.");
		
		Client user = (Client) target;
		
		if (!user.getPassword().equals(repeatPassword)) {
			errors.rejectValue("password", "field.required", "Passwords must match.");
		}

		ValidationUtils.rejectIfEmpty(errors, "email", "field.required", "Email not be empty.");

		if (emailBusy) {
			errors.rejectValue("email", "field.required", "This email is already exists.");
		}

		ValidationUtils.rejectIfEmpty(errors, "phone", "field.required", "Phone not be empty.");

	}

	public void setRepeatPassword(String password) {
		this.repeatPassword = password;
	}

	public void loginBusy(boolean busy) {
		this.loginBusy = busy;
	}

	public void emailBusy(boolean busy) {
		this.emailBusy = busy;
	}
}
